package com.gzz.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzz.mapper.ImgsRespMapper;
import com.gzz.pojo.GoodsInfo;
import com.gzz.mapper.GoodsInfoMapper;
import com.gzz.pojo.ImgsResp;
import com.gzz.service.GoodsInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzz.vo.FoodVo;
import com.gzz.vo.GoodsVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.gzz.utils.OssUtils.FoodType;
import static com.gzz.utils.OssUtils.GoodTypeId;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 */
@Service
public class GoodsInfoServiceImpl extends ServiceImpl<GoodsInfoMapper, GoodsInfo> implements GoodsInfoService {

    @Resource
    GoodsInfoMapper goodsInfoMapper;
    @Resource
    ImgsRespMapper imgsRespMapper;
    @Override
    public List<GoodsVo> getVo(List<GoodsInfo> goodsInfoList) {
        List<GoodsVo> goodsVoList = new ArrayList<>();
        for(GoodsInfo goodsInfo : goodsInfoList)
        {
            GoodsVo goodsVo = new GoodsVo();
            BeanUtils.copyProperties(goodsInfo,goodsVo);
            QueryWrapper<ImgsResp> imgsRespQueryWrapper = new QueryWrapper<>();
            imgsRespQueryWrapper.eq("st_id",goodsInfo.getGoodsId())
                    .eq("type_id",GoodTypeId);
            List<ImgsResp> imgsRespList = imgsRespMapper.selectList(imgsRespQueryWrapper);
            List<String> stringList = new ArrayList<>();
            for(ImgsResp imgsResp : imgsRespList)
            {
                stringList.add(imgsResp.getImageUrl());
            }
            goodsVo.setImgs(stringList);
            goodsVoList.add(goodsVo);
        }
        return goodsVoList;
    }
    @Override
    public int removeByIdAndTypeId(Long stId, Integer goodTypeId) {
        //通过id,和typeId删除数据库的图片路径
        LambdaQueryWrapper<ImgsResp> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ImgsResp::getTypeId,GoodTypeId).eq(ImgsResp::getStId,stId);

        int  r = imgsRespMapper.delete(lambdaQueryWrapper);
        return  r;
    }



    @Override
    public void saveVo(GoodsVo goodsVo) {
        GoodsInfo goodsInfo = new GoodsInfo();
        BeanUtils.copyProperties(goodsVo,goodsInfo);
        Long id = (long)Math.abs(UUID.randomUUID().hashCode());
        goodsInfo.setGoodsId(id);
        if(goodsVo.getImgs()!=null){
            for(String url: goodsVo.getImgs())
            {
                ImgsResp imgsResp = new ImgsResp();
                imgsResp.setImageUrl(url);
                imgsResp.setStId(goodsInfo.getGoodsId());
                imgsResp.setTypeId(GoodTypeId);
                imgsRespMapper.insert(imgsResp);
            }
        }

        goodsInfoMapper.insert(goodsInfo);
    }
}
